package book.ch9;


import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

class Police implements KeyListener, FocusListener {
    Win view;
    public void setView(Win view){
        this.view = view;
    }
    public void keyTyped(KeyEvent e) {
        JTextField text=(JTextField)e.getSource();
        if(text.getText().length()==6){
            text.setEnabled(false);
            text.transferFocus();
        }
    }
    public void keyPressed(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}
    public void focusGained(FocusEvent e) {
        if(e.getSource()==view.button){
            for(int i=0;i<3;i++) {
                view.text[i].setEnabled(true);
            }
        }
        if(e.getSource() instanceof JTextField){
            JTextField text=(JTextField)e.getSource();
            text.setText(null);
        }

    }
    public void focusLost(FocusEvent e){}
}


class Win extends JFrame {
    JTextField text[]=new JTextField[3];
    Police police;
    JButton button;
    public Win() {
        setLayout(new FlowLayout());
        Font font = new Font("宋体",Font.BOLD,36);
        police = new Police();
        police.setView(this);//将当前窗口传递给police组合的窗口
        for(int i=0;i<3;i++) {
            text[i]=new JTextField(20);
            text[i].addKeyListener(police);  //监视键盘事件
            text[i].addFocusListener(police);//监视焦点事件
            add(text[i]);
            text[i].setFont(font);
        }
        button=new JButton("确定");
        button.addFocusListener(police);
        button.setFont(font);
        add(button);
        setVisible(true);
        //窗体可见之后，  text[0]首先有输入焦点
        text[0].requestFocusInWindow();
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
}

public class E9_12 {
    public static void main(String args[]) {
        Win win=new Win();
        win.setTitle("输入序列号");
        win.setBounds(10,10,460,360);
    }
}
